using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CodRevit.ViewModels;

namespace CodRevit.Handlers
{
    public class ChangeCategoryHandler : IExternalEventHandler
    {
        private readonly UIApplication _uiApp;
        private List<FamilyInstance> _familyInstances = new();
        private BuiltInCategory _targetCategory;
        private ChangeCategoryViewModel? _viewModel;

        public ChangeCategoryHandler(UIApplication uiApp)
        {
            _uiApp = uiApp;
        }

        public void SetParameters(List<FamilyInstance> familyInstances, BuiltInCategory targetCategory, ChangeCategoryViewModel viewModel)
        {
            _familyInstances = familyInstances;
            _targetCategory = targetCategory;
            _viewModel = viewModel;
        }

        public void Execute(UIApplication app)
        {
            var processedFamilies = new List<string>();
            var doc = app.ActiveUIDocument.Document;

            try
            {
                System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 开始处理，总共 {_familyInstances.Count} 个族实例");
                
                // 验证输入参数
                if (!_familyInstances.Any())
                {
                    _viewModel?.OnProcessFailed("没有有效的族实例可处理");
                    return;
                }

                // 按照参考代码的方式筛选族（去重，排除就地族）
                var familyList = (from x in (from x in _familyInstances
                                             select x.Symbol.Family into x
                                             where !x.IsInPlace
                                             select x.Id).Distinct()
                                 select doc.GetElement(x) as Family).ToList();

                System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 找到 {familyList.Count} 个非就地族");

                if (!familyList.Any())
                {
                    _viewModel?.OnProcessFailed("没有找到有效的非就地族");
                    return;
                }

                // 按照参考代码的方式使用简单的for循环
                for (int i = 0; i < familyList.Count; i++)
                {
                    Family family = familyList[i];
                    
                    if (family == null || !family.IsValidObject)
                    {
                        System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 族 {i} 无效，跳过");
                        continue;
                    }

                    // 保存族名称，因为在EditFamily后原对象可能失效
                    string familyName = family.Name;
                    
                    // 按照参考代码的方式检查类别
                    bool flag = family.FamilyCategoryId == new ElementId((int)_targetCategory);
                    if (!flag) // 如果不是目标类别，才需要修改
                    {
                        Document famDoc = null;
                        try
                        {
                            System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 开始修改族 {familyName} 的类别");
                            
                            // 打开族文档进行编辑
                            famDoc = doc.EditFamily(family);
                            
                            // 在族文档中进行修改
                            using (Transaction transFam = new Transaction(famDoc, "修改族类型"))
                            {
                                transFam.Start();
                                famDoc.OwnerFamily.FamilyCategoryId = new ElementId((int)_targetCategory);
                                transFam.Commit();
                            }
                            
                            // 重新载入族到项目文档
                            famDoc.LoadFamily(doc, new FamilyLoadOptions());
                            
                            processedFamilies.Add(familyName);
                            System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 族 {familyName} 修改成功");
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 处理族 {familyName} 时出错: {ex.Message}");
                            // 继续处理其他族，不中断整个流程
                        }
                        finally
                        {
                            // 确保族文档被正确关闭（如果需要的话）
                            // 注意：LoadFamily 通常会自动关闭族文档，所以这里不需要显式关闭
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 族 {family.Name} 已经是目标类别，跳过");
                    }
                }

                // 通知ViewModel处理完成
                if (_viewModel != null)
                {
                    var message = processedFamilies.Any() 
                        ? $"成功修改了 {processedFamilies.Count} 个族的类别" 
                        : "没有族被成功修改";
                    System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 处理完成: {message}");
                    _viewModel.OnProcessCompleted(processedFamilies, message);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[ChangeCategoryHandler] 总体异常: {ex.Message}\n堆栈: {ex.StackTrace}");
                _viewModel?.OnProcessFailed(ex.Message);
            }
        }

        public string GetName()
        {
            return "ChangeCategoryHandler";
        }
    }

    public class FamilyLoadOptions : IFamilyLoadOptions
    {
        public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
        {
            overwriteParameterValues = true;
            return true; // 覆盖现有族
        }

        public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues)
        {
            source = FamilySource.Family;
            overwriteParameterValues = true;
            return true; // 覆盖现有族
        }
    }
}